<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['add', 'remove', 'refresh', 'columnDisplay']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" :pagination="false" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <PopupForm
      v-if="
        (JSON.stringify(schedule.equipmentScheduleInfo) !== '{}' &&
          baTable.form.operate) ||
        baTable.form.operate === 'edit'
      "
    />
  </div>
</template>
<script lang="ts" setup>
import {
  ref,
  provide,
  onMounted,
  reactive,
  onBeforeUnmount,
  inject,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import { FactorySchedule } from "@/api/backend/index";
import PopupForm from "./schedulePopupForm.vue";
import { useRoute, useRouter } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useNavTabs } from "@/store/navTabs";
import { getDictData } from "@/utils/common";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useProductionPlan } from "@/store/backend/ProductionPlan/plan";
import { useBomM } from "@/store/backend/BomM/bomM";
import { useBomDict } from "@/store/backend/BomM/bomDict";
import { useFactoryStation } from "@/store/backend/FactoryM/stationInfo";
import { useProductionWorkOrder } from "@/store/backend/ProductionPlan/workOrder";
import { useFactoryEquipment } from "@/store/backend/FactoryM/equipmentUnit";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const plan = useProductionPlan();
const bom = useBomM();
const bomD = useBomDict();
const station = useFactoryStation();
const planOrder = useProductionWorkOrder();
const equipment = useFactoryEquipment();
// const equipClassType = inject("equipClassType") as any;
const schedule = inject("schedule") as any;

//全局事件总线
const { proxy } = useCurrentInstance();

const state: {} = reactive({});

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + FactorySchedule)
      ? (navTabs as any).pageSizeMap.get(route.path + FactorySchedule)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(FactorySchedule), //this.api = api部门管理
  {
    expandAll: true,
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("name"),
        label: "名称",
        prop: "name",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("startDate"),
        label: "起始日期",
        prop: "startDate",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("endDate"),
        label: "结束日期",
        prop: "endDate",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("className"),
        label: "班次",
        prop: "className",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("priority"),
        label: "优先级",
        prop: "priority",
        align: "center",
      },
      {
        show: filedShowOff("monday"),
        label: "周一",
        prop: "monday",
        align: "center",
      },
      {
        show: filedShowOff("tuesday"),
        label: "周二",
        prop: "tuesday",
        align: "center",
      },
      {
        show: filedShowOff("wednesday"),
        label: "周三",
        prop: "wednesday",
        align: "center",
      },
      {
        show: filedShowOff("thursday"),
        label: "周四",
        prop: "thursday",
        align: "center",
      },
      {
        show: filedShowOff("friday"),
        label: "周五",
        prop: "friday",
        align: "center",
      },
      {
        show: filedShowOff("saturday"),
        label: "周六",
        prop: "saturday",
        align: "center",
      },
      {
        show: filedShowOff("sunday"),
        label: "周日",
        prop: "sunday",
        align: "center",
      },
      {
        label: "操作",
        align: "center",
        operator: false,
        render: "buttons",
        fixed: "right",
        width: "150",
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {},
  },
  // 操作前置方法列表，返回false则取消原操作
  {},
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {
    onSubmit: ({ res }: { res: ApiResponse }) => {
      console.log("表单提交后刷新", schedule.backupSearch);
      //提交工厂日历数据后刷新工厂日历记录数据
      setTimeout(() => {
        proxy.eventBus.emit("getScheduleOfFactory", schedule.backupSearch);
      }, 500);
    }, // 表单提交后
  }
);

interface ApiResponse<T = any> {
  code: number;
  data: T;
  msg: string;
  time: number;
}
//获取计划状态/是否暂停的字典
const getMenuStatus = () => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["productType"])
  ) {
    dictionary.getDictInfo("sys_plan_producttype").then((res: any) => {
      dictionary.moreTags["productType"] = getDictData(res);
      plan.options["productType"] = res;
      console.log("获取生产类型的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["priority"])
  ) {
    dictionary.getDictInfo("sys_plan_priority").then((res: any) => {
      dictionary.moreTags["priority"] = getDictData(res);
      plan.options["priority"] = res;
      console.log("获取优先级的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["isProduct"])
  ) {
    dictionary.getDictInfo("sys_plan_isproduct").then((res: any) => {
      dictionary.moreTags["isProduct"] = getDictData(res);
      plan.options["isProduct"] = res;
      console.log("获取是否排产的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["state"])
  ) {
    dictionary.getDictInfo("sys_workorder_state").then((res: any) => {
      dictionary.moreTags["state"] = getDictData(res);
      plan.options["state"] = res;
      console.log("获取是否排产的字典", dictionary.moreTags);
    });
  }
};
getMenuStatus();

//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  planOrder.$patch((state) => {
    state.single = row;
    state.planId = row.id;
  });
  router.push({
    path: "/admin/ProductionWorkOrder/detail",
    query: { materialCode: row.productCode, materialType: row.materialType },
  });
};

planOrder.$subscribe((state: any) => {
  const storeOrder = (data: any[]) => {
    for (let i = 0, len = data.length; i < len; i++) {
      if (data[i].key === "getOrder") {
        return true;
      }
    }
    return false;
  };
  if (storeOrder(state.events)) {
    baTable.getList(FactorySchedule);
  }
});
//查询工厂日历与工厂日历记录数据
const getScheduleOfFactory = () => {};
//查询工厂日历数据
proxy.eventBus.on("getScheduleOfFactory", (res: any) => {
  console.log("查询工厂日历数据", res);
  //从设备排班方式仓库拿取设备数据
  baTable.comSearch.form.equipmentCode =
    schedule.equipmentScheduleInfo.equipmentCode; //设备编号
  // baTable.comSearch.form.name = schedule.equipmentScheduleInfo.label; //日历名称
  if (res.type == "dept") {
    //部门日历查询
    baTable.comSearch.form.deptId = schedule.equipmentScheduleInfo.id; //日历部门
    baTable.comSearch.form.ancestors = schedule.equipmentScheduleInfo.ancestors; //日历祖级数据
  } else if (res.type == "equip") {
    baTable.comSearch.form.deptId = schedule.equipmentScheduleInfo.deptId; //日历部门
  } else {
    baTable.comSearch.form.deptId = schedule.equipmentScheduleInfo.id; //日历部门
    baTable.comSearch.form.ancestors = schedule.equipmentScheduleInfo.ancestors; //日历祖级数据
  }

  baTable.getList(FactorySchedule);
});

//派工
const toggleDispatch = (id: number, row: any) => {
  proxy.eventBus.emit("workOrderDrawer");
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(FactorySchedule);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */

  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {}
  );
});
onBeforeUnmount(() => {
  proxy.eventBus.off("getScheduleOfFactory");
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("plan", plan);
provide("bom", bom);
provide("bomD", bomD);
provide("station", station);
provide("equipment", equipment);
</script>
<style lang="scss" scoped>
.default-main {
  margin: 0px !important;
  margin-bottom: 30px !important;
}
</style>
